cmake_minimum_required(VERSION 3.10)

# ==================== 测试项目配置 ====================
project(game_microservices_Tests)

# 设置C++标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# ==================== 编译选项配置 ====================
if(PLATFORM_WINDOWS)
    # Windows特定设置
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
    add_definitions(-DWIN32_LEAN_AND_MEAN -DNOMINMAX -DPLATFORM_WINDOWS)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
else()
    # Linux/Unix特定设置
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pthread")
    add_definitions(-DPLATFORM_LINUX)
endif()

# ==================== 包含目录配置 ====================
include_directories(${CMAKE_SOURCE_DIR}/include)
include_directories(${CMAKE_SOURCE_DIR}/include/common)

# 打印调试信息
message(STATUS "CMAKE_SOURCE_DIR: ${CMAKE_SOURCE_DIR}")
message(STATUS "Include directories: ${CMAKE_SOURCE_DIR}/include")

# ==================== 依赖库配置 ====================
# 检查网络模块源文件
set(NETWORK_SOURCES
        "${CMAKE_SOURCE_DIR}/src/common/network/inet_address.cpp"
        "${CMAKE_SOURCE_DIR}/src/common/network/socket.cpp"
        "${CMAKE_SOURCE_DIR}/src/common/network/channel.cpp"
        "${CMAKE_SOURCE_DIR}/src/common/network/epoll.cpp"
        "${CMAKE_SOURCE_DIR}/src/common/network/event_loop.cpp"
)

# 检查Logger模块源文件
set(LOGGER_SOURCES
        "${CMAKE_SOURCE_DIR}/src/common/logger/logger.cpp"
)

# 验证源文件存在
foreach(SOURCE ${NETWORK_SOURCES})
    if(EXISTS ${SOURCE})
        message(STATUS "Found network source: ${SOURCE}")
    else()
        message(WARNING "Missing network source: ${SOURCE}")
    endif()
endforeach()

foreach(SOURCE ${LOGGER_SOURCES})
    if(EXISTS ${SOURCE})
        message(STATUS "Found logger source: ${SOURCE}")
    else()
        message(WARNING "Missing logger source: ${SOURCE}")
    endif()
endforeach()

# ==================== 创建Config库（其他库的依赖） ====================
# 检查Config模块源文件
set(CONFIG_SOURCES
    "${CMAKE_SOURCE_DIR}/src/common/config/config_manager.cpp"
)

# 验证Config源文件存在
set(CONFIG_SOURCES_FOUND TRUE)
foreach(SOURCE ${CONFIG_SOURCES})
    if(EXISTS ${SOURCE})
        message(STATUS "Found Config source: ${SOURCE}")
    else()
        message(WARNING "Missing Config source: ${SOURCE}")
        set(CONFIG_SOURCES_FOUND FALSE)
    endif()
endforeach()

if(CONFIG_SOURCES_FOUND)
    # 创建Config库
    add_library(temp_config_lib STATIC ${CONFIG_SOURCES})
    target_include_directories(temp_config_lib PUBLIC
        ${CMAKE_SOURCE_DIR}/include
        ${CMAKE_SOURCE_DIR}/include/common
    )
    target_compile_features(temp_config_lib PUBLIC cxx_std_17)
    target_link_libraries(temp_config_lib PUBLIC pthread)

    # 查找yaml-cpp库
    find_package(yaml-cpp QUIET)
    if(yaml-cpp_FOUND)
        target_link_libraries(temp_config_lib PUBLIC yaml-cpp)
        target_compile_definitions(temp_config_lib PUBLIC YAML_CPP_FOUND)
        message(STATUS "Found yaml-cpp for Config module")
    else()
        # 尝试手动查找yaml-cpp
        find_path(YAML_CPP_INCLUDE_DIR
            NAMES yaml-cpp/yaml.h
            PATHS
                /usr/include
                /usr/local/include
                /opt/yaml-cpp/include
        )

        find_library(YAML_CPP_LIBRARY
            NAMES yaml-cpp libyaml-cpp
            PATHS
                /usr/lib
                /usr/local/lib
                /opt/yaml-cpp/lib
                /usr/lib/x86_64-linux-gnu
        )

        if(YAML_CPP_INCLUDE_DIR AND YAML_CPP_LIBRARY)
            target_include_directories(temp_config_lib PUBLIC ${YAML_CPP_INCLUDE_DIR})
            target_link_libraries(temp_config_lib PUBLIC ${YAML_CPP_LIBRARY})
            target_compile_definitions(temp_config_lib PUBLIC YAML_CPP_FOUND)
            message(STATUS "Found yaml-cpp manually: ${YAML_CPP_LIBRARY}")
        else()
            message(WARNING "yaml-cpp not found. YAML support will be limited.")
        endif()
    endif()

    # 查找nlohmann/json库
    find_package(nlohmann_json QUIET)
    if(nlohmann_json_FOUND)
        target_link_libraries(temp_config_lib PUBLIC nlohmann_json::nlohmann_json)
        target_compile_definitions(temp_config_lib PUBLIC NLOHMANN_JSON_FOUND)
        message(STATUS "Found nlohmann/json for Config module")
    else()
        # 尝试手动查找nlohmann/json
        find_path(NLOHMANN_JSON_INCLUDE_DIR
            NAMES nlohmann/json.hpp
            PATHS
                /usr/include
                /usr/local/include
                /opt/nlohmann/include
        )

        if(NLOHMANN_JSON_INCLUDE_DIR)
            target_include_directories(temp_config_lib PUBLIC ${NLOHMANN_JSON_INCLUDE_DIR})
            target_compile_definitions(temp_config_lib PUBLIC NLOHMANN_JSON_FOUND)
            message(STATUS "Found nlohmann/json manually: ${NLOHMANN_JSON_INCLUDE_DIR}")
        else()
            message(WARNING "nlohmann/json not found. JSON support will be limited.")
        endif()
    endif()

    set(CONFIG_LIB temp_config_lib)
    message(STATUS "Config library created successfully")
else()
    message(WARNING "Config library creation failed - missing sources")
    set(CONFIG_LIB "")
endif()

# 创建ThreadPool库（网络测试需要，因为Logger依赖ThreadPool）
set(THREAD_POOL_SOURCES
    "${CMAKE_SOURCE_DIR}/src/common/thread_pool/thread_pool.cpp"
)

if(EXISTS "${CMAKE_SOURCE_DIR}/src/common/thread_pool/thread_pool.cpp")
    add_library(temp_thread_pool_lib STATIC ${THREAD_POOL_SOURCES})
    target_include_directories(temp_thread_pool_lib PUBLIC
        ${CMAKE_SOURCE_DIR}/include
    )
    target_compile_features(temp_thread_pool_lib PUBLIC cxx_std_17)
    target_link_libraries(temp_thread_pool_lib PUBLIC pthread)
    set(THREAD_POOL_LIB temp_thread_pool_lib)
    message(STATUS "Created ThreadPool library for network tests")
else()
    set(THREAD_POOL_LIB "")
    message(WARNING "ThreadPool source not found, some tests may fail")
endif()

# 创建Logger库
add_library(temp_logger_lib STATIC ${LOGGER_SOURCES})
target_include_directories(temp_logger_lib PUBLIC
        ${CMAKE_SOURCE_DIR}/include
        ${CMAKE_SOURCE_DIR}/include/common
)
target_link_libraries(temp_logger_lib PUBLIC
    pthread
    $<$<BOOL:${CONFIG_LIB}>:${CONFIG_LIB}>
    # ThreadPool依赖将在使用Logger的地方添加
)

# 创建网络库
add_library(temp_network_lib STATIC ${NETWORK_SOURCES})
target_include_directories(temp_network_lib PUBLIC
        ${CMAKE_SOURCE_DIR}/include
        ${CMAKE_SOURCE_DIR}/include/common
)
target_link_libraries(temp_network_lib PUBLIC
        pthread
        temp_logger_lib
        $<$<BOOL:${CONFIG_LIB}>:${CONFIG_LIB}>
)

# 设置库变量
set(NETWORK_LIB temp_network_lib)
set(LOGGER_LIB temp_logger_lib)

# ==================== 启用测试 ====================
enable_testing()

# ==================== 主要测试目标 ====================
# 网络模块综合测试（仅Linux/macOS）
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/network_module_comprehensive_test.cpp")
    if(PLATFORM_LINUX OR PLATFORM_MACOS)
        add_executable(network_comprehensive_test network_module_comprehensive_test.cpp)

        target_include_directories(network_comprehensive_test PRIVATE
                ${CMAKE_SOURCE_DIR}/include
        )

        target_link_libraries(network_comprehensive_test
                ${NETWORK_LIB}
                ${LOGGER_LIB}
                ${THREAD_POOL_LIB}  # 添加ThreadPool库，因为Logger依赖它
                pthread
        )

        # 添加测试
        add_test(NAME NetworkComprehensiveTest COMMAND network_comprehensive_test)
        set_tests_properties(NetworkComprehensiveTest PROPERTIES
                TIMEOUT 300  # 5分钟超时
                PASS_REGULAR_EXPRESSION "所有测试通过"
        )

        message(STATUS "Added NetworkComprehensiveTest")
    else()
        message(STATUS "Skipping NetworkComprehensiveTest on Windows (requires Linux-specific features)")
    endif()
else()
    message(WARNING "network_module_comprehensive_test.cpp not found")
endif()

# Kafka综合测试
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/kafka_comprehensive_test.cpp")
    # 检查Kafka相关源文件
    set(KAFKA_SOURCES
        "${CMAKE_SOURCE_DIR}/src/common/kafka/kafka_producer.cpp"
        "${CMAKE_SOURCE_DIR}/src/common/kafka/kafka_consumer.cpp"
    )

    # 验证Kafka源文件存在
    set(KAFKA_SOURCES_FOUND TRUE)
    foreach(SOURCE ${KAFKA_SOURCES})
        if(EXISTS ${SOURCE})
            message(STATUS "Found Kafka source: ${SOURCE}")
        else()
            message(WARNING "Missing Kafka source: ${SOURCE}")
            set(KAFKA_SOURCES_FOUND FALSE)
        endif()
    endforeach()

    if(KAFKA_SOURCES_FOUND)
        # 检查ThreadPool源文件（Kafka依赖ThreadPool）
        set(THREAD_POOL_SOURCES_FOR_KAFKA
            "${CMAKE_SOURCE_DIR}/src/common/thread_pool/thread_pool.cpp"
        )

        set(THREAD_POOL_FOUND TRUE)
        foreach(SOURCE ${THREAD_POOL_SOURCES_FOR_KAFKA})
            if(EXISTS ${SOURCE})
                message(STATUS "Found ThreadPool source for Kafka: ${SOURCE}")
            else()
                message(WARNING "Missing ThreadPool source for Kafka: ${SOURCE}")
                set(THREAD_POOL_FOUND FALSE)
            endif()
        endforeach()

        if(NOT THREAD_POOL_FOUND)
            message(WARNING "Skipping KafkaComprehensiveTest due to missing ThreadPool dependency")
        else()
            # 创建ThreadPool库（如果还没有创建）
            if(NOT TARGET temp_thread_pool_lib_for_kafka)
                add_library(temp_thread_pool_lib_for_kafka STATIC ${THREAD_POOL_SOURCES_FOR_KAFKA})
                target_include_directories(temp_thread_pool_lib_for_kafka PUBLIC
                    ${CMAKE_SOURCE_DIR}/include
                )
                target_compile_features(temp_thread_pool_lib_for_kafka PUBLIC cxx_std_17)
                target_link_libraries(temp_thread_pool_lib_for_kafka PUBLIC pthread ${LOGGER_LIB})
            endif()

            # 创建Kafka库
            add_library(temp_kafka_lib STATIC ${KAFKA_SOURCES})
            target_include_directories(temp_kafka_lib PUBLIC
                ${CMAKE_SOURCE_DIR}/include
                ${CMAKE_SOURCE_DIR}/include/common
            )
            target_link_libraries(temp_kafka_lib PUBLIC
                temp_config_lib
                temp_thread_pool_lib_for_kafka
                ${LOGGER_LIB}
                pthread
            )

            # 尝试找到librdkafka
            find_library(RDKAFKA_LIB rdkafka++)
            if(RDKAFKA_LIB)
                target_link_libraries(temp_kafka_lib PUBLIC ${RDKAFKA_LIB})
                message(STATUS "Found librdkafka: ${RDKAFKA_LIB}")
            else()
                message(WARNING "librdkafka not found, using mock implementation")
            endif()

            # 创建Kafka综合测试
            add_executable(kafka_comprehensive_test kafka_comprehensive_test.cpp)

            target_include_directories(kafka_comprehensive_test PRIVATE
                ${CMAKE_SOURCE_DIR}/include
            )

            target_link_libraries(kafka_comprehensive_test
                temp_kafka_lib
                temp_config_lib
                temp_thread_pool_lib_for_kafka
                ${LOGGER_LIB}
                pthread
            )

            # 如果找到librdkafka，链接它
            if(RDKAFKA_LIB)
                target_link_libraries(kafka_comprehensive_test ${RDKAFKA_LIB})
            endif()
            # 添加测试
            add_test(NAME KafkaComprehensiveTest COMMAND kafka_comprehensive_test)
            set_tests_properties(KafkaComprehensiveTest PROPERTIES
                TIMEOUT 120  # 2分钟超时
                PASS_REGULAR_EXPRESSION "所有Kafka测试通过"
            )

            message(STATUS "Added KafkaComprehensiveTest")

            # 添加简化的Kafka测试（用于验证链接问题修复）
            if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/kafka_simple_test.cpp")
                add_executable(kafka_simple_test kafka_simple_test.cpp)

                target_include_directories(kafka_simple_test PRIVATE
                    ${CMAKE_SOURCE_DIR}/include
                )

                target_link_libraries(kafka_simple_test
                    temp_kafka_lib
                    temp_config_lib
                    temp_thread_pool_lib_for_kafka
                    ${LOGGER_LIB}
                    pthread
                )

                # 如果找到librdkafka，链接它
                if(RDKAFKA_LIB)
                    target_link_libraries(kafka_simple_test ${RDKAFKA_LIB})
                endif()

                message(STATUS "Added kafka_simple_test for link verification")
            endif()

            # 添加Kafka调试测试（用于调试阻塞问题）
            if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/kafka_debug_test.cpp")
                add_executable(kafka_debug_test kafka_debug_test.cpp)

                target_include_directories(kafka_debug_test PRIVATE
                    ${CMAKE_SOURCE_DIR}/include
                )

                target_link_libraries(kafka_debug_test
                    temp_kafka_lib
                    temp_config_lib
                    temp_thread_pool_lib_for_kafka
                    ${LOGGER_LIB}
                    pthread
                )

                # 如果找到librdkafka，链接它
                if(RDKAFKA_LIB)
                    target_link_libraries(kafka_debug_test ${RDKAFKA_LIB})
                endif()

                message(STATUS "Added kafka_debug_test for debugging blocking issues")
            endif()

        endif()  # THREAD_POOL_FOUND
    else()
        message(WARNING "Skipping KafkaComprehensiveTest due to missing Kafka sources")
    endif()
else()
    message(WARNING "kafka_comprehensive_test.cpp not found")
endif()

# 通用模块综合测试
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/common_modules_comprehensive_test.cpp")
    # 检查通用模块源文件
    set(THREAD_POOL_SOURCES
        "${CMAKE_SOURCE_DIR}/src/common/thread_pool/thread_pool.cpp"
    )
    set(SCHEDULER_SOURCES
        "${CMAKE_SOURCE_DIR}/src/common/scheduler/task_scheduler.cpp"
    )
    set(DATABASE_SOURCES
        "${CMAKE_SOURCE_DIR}/src/common/database/mysql_pool.cpp"
    )

    # 验证通用模块源文件存在
    set(COMMON_MODULES_FOUND TRUE)

    # 检查线程池
    foreach(SOURCE ${THREAD_POOL_SOURCES})
        if(EXISTS ${SOURCE})
            message(STATUS "Found thread pool source: ${SOURCE}")
        else()
            message(WARNING "Missing thread pool source: ${SOURCE}")
            set(COMMON_MODULES_FOUND FALSE)
        endif()
    endforeach()

    # 检查调度器
    foreach(SOURCE ${SCHEDULER_SOURCES})
        if(EXISTS ${SOURCE})
            message(STATUS "Found scheduler source: ${SOURCE}")
        else()
            message(WARNING "Missing scheduler source: ${SOURCE}")
            set(COMMON_MODULES_FOUND FALSE)
        endif()
    endforeach()

    if(COMMON_MODULES_FOUND)
        # ThreadPool库已经在前面创建了，这里不需要重复创建
        # 确保THREAD_POOL_LIB变量已设置
        if(NOT THREAD_POOL_LIB)
            set(THREAD_POOL_LIB temp_thread_pool_lib)
        endif()

        # 创建调度器库
        add_library(temp_task_scheduler_lib STATIC ${SCHEDULER_SOURCES})
        target_include_directories(temp_task_scheduler_lib PUBLIC
            ${CMAKE_SOURCE_DIR}/include
        )
        target_compile_features(temp_task_scheduler_lib PUBLIC cxx_std_17)
        target_link_libraries(temp_task_scheduler_lib PUBLIC
            pthread
            temp_thread_pool_lib  # TaskScheduler依赖ThreadPool
            ${LOGGER_LIB}         # TaskScheduler也使用Logger
        )

        # 设置库变量
        set(THREAD_POOL_LIB temp_thread_pool_lib)
        set(TASK_SCHEDULER_LIB temp_task_scheduler_lib)

        # 创建通用模块综合测试
        add_executable(common_modules_comprehensive_test common_modules_comprehensive_test.cpp)

        target_include_directories(common_modules_comprehensive_test PRIVATE
            ${CMAKE_SOURCE_DIR}/include
        )

        target_compile_features(common_modules_comprehensive_test PRIVATE cxx_std_17)

        # 基础库链接
        target_link_libraries(common_modules_comprehensive_test
            temp_thread_pool_lib
            temp_task_scheduler_lib
            ${LOGGER_LIB}
            pthread
        )

        # 条件链接MySQL数据库库
        # 首先尝试查找MySQL Connector/C++
        find_path(MYSQL_CONNECTOR_INCLUDE_DIR
            NAMES mysql_driver.h
            PATHS
                /usr/include
                /usr/local/include
                /usr/include/mysql-cppconn
                /usr/local/include/mysql-cppconn
                /opt/mysql/include
            PATH_SUFFIXES mysql-cppconn cppconn
        )

        find_library(MYSQL_CONNECTOR_LIBRARY
            NAMES mysqlcppconn mysqlcppconn-static
            PATHS
                /usr/lib
                /usr/local/lib
                /usr/lib/mysql
                /usr/local/lib/mysql
                /opt/mysql/lib
                /usr/lib/x86_64-linux-gnu
            PATH_SUFFIXES mysql
        )

        if(MYSQL_CONNECTOR_INCLUDE_DIR AND MYSQL_CONNECTOR_LIBRARY)
            set(MYSQL_FOUND TRUE)
            set(MYSQL_INCLUDE_DIRS ${MYSQL_CONNECTOR_INCLUDE_DIR})
            set(MYSQL_LIBRARIES ${MYSQL_CONNECTOR_LIBRARY})
            message(STATUS "Found MySQL Connector/C++: ${MYSQL_CONNECTOR_LIBRARY}")
        else()
            # 如果没有找到MySQL Connector/C++，尝试查找MySQL C API
            find_package(PkgConfig QUIET)
            if(PkgConfig_FOUND)
                pkg_check_modules(MYSQL QUIET mysqlclient)
            endif()

            if(NOT MYSQL_FOUND)
                find_path(MYSQL_INCLUDE_DIR
                    NAMES mysql/mysql.h mysql.h
                    PATHS
                        /usr/include
                        /usr/local/include
                        /usr/include/mysql
                        /usr/local/include/mysql
                        /opt/mysql/include
                    PATH_SUFFIXES mysql
                )

                find_library(MYSQL_LIBRARY
                    NAMES mysqlclient mysql libmysql
                    PATHS
                        /usr/lib
                        /usr/local/lib
                        /usr/lib/mysql
                        /usr/local/lib/mysql
                        /opt/mysql/lib
                        /usr/lib/x86_64-linux-gnu
                    PATH_SUFFIXES mysql
                )

                if(MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
                    set(MYSQL_FOUND TRUE)
                    set(MYSQL_INCLUDE_DIRS ${MYSQL_INCLUDE_DIR})
                    set(MYSQL_LIBRARIES ${MYSQL_LIBRARY})
                    message(STATUS "Found MySQL C API: ${MYSQL_LIBRARY}")
                endif()
            endif()
        endif()

        # 重新启用MySQL测试
        message(STATUS "Attempting to find MySQL libraries for database tests...")

        # 安装说明
        message(STATUS "如果MySQL库未找到，请安装:")
        message(STATUS "  Ubuntu/Debian: sudo apt-get install libmysqlcppconn-dev")
        message(STATUS "  CentOS/RHEL: sudo yum install mysql-connector-c++-devel")

        # 重新启用MySQL相关的链接代码
        if(MYSQL_FOUND)
            # 检查数据库源文件
            foreach(SOURCE ${DATABASE_SOURCES})
                if(EXISTS ${SOURCE})
                    message(STATUS "Found database source: ${SOURCE}")
                else()
                    message(WARNING "Missing database source: ${SOURCE}")
                endif()
            endforeach()

            add_library(temp_database_lib STATIC ${DATABASE_SOURCES})
            target_include_directories(temp_database_lib PUBLIC
                ${CMAKE_SOURCE_DIR}/include
                ${MYSQL_INCLUDE_DIRS}
            )
            target_compile_features(temp_database_lib PUBLIC cxx_std_17)
            target_link_libraries(temp_database_lib PUBLIC
                pthread
                ${MYSQL_LIBRARIES}
            )

            target_link_libraries(common_modules_comprehensive_test temp_database_lib)
            target_compile_definitions(common_modules_comprehensive_test PRIVATE MYSQL_FOUND)
            message(STATUS "MySQL found for common modules test: ${MYSQL_LIBRARIES}")
        else()
            message(STATUS "MySQL not found. Database tests will be skipped in common modules test.")
            message(STATUS "To enable database tests, install MySQL Connector/C++ and rerun cmake.")
        endif()

        # 条件链接Redis库
        find_path(REDIS_INCLUDE_DIR
            NAMES hiredis/hiredis.h
            PATHS
                /usr/include
                /usr/local/include
                /opt/redis/include
            PATH_SUFFIXES hiredis
        )

        find_library(REDIS_LIBRARY
            NAMES hiredis
            PATHS
                /usr/lib
                /usr/local/lib
                /opt/redis/lib
                /usr/lib/x86_64-linux-gnu
        )

        if(REDIS_INCLUDE_DIR AND REDIS_LIBRARY)
            set(REDIS_FOUND TRUE)
            set(REDIS_INCLUDE_DIRS ${REDIS_INCLUDE_DIR})
            set(REDIS_LIBRARIES ${REDIS_LIBRARY})
            message(STATUS "Found Redis hiredis library: ${REDIS_LIBRARY}")

            # 检查Redis源文件
            set(REDIS_SOURCES
                ${CMAKE_SOURCE_DIR}/src/common/database/redis_pool.cpp
            )

            foreach(SOURCE ${REDIS_SOURCES})
                if(EXISTS ${SOURCE})
                    message(STATUS "Found Redis source: ${SOURCE}")
                else()
                    message(WARNING "Missing Redis source: ${SOURCE}")
                endif()
            endforeach()

            # 创建Redis库
            add_library(temp_redis_lib STATIC ${REDIS_SOURCES})
            target_include_directories(temp_redis_lib PUBLIC
                ${CMAKE_SOURCE_DIR}/include
                ${REDIS_INCLUDE_DIRS}
            )
            target_compile_features(temp_redis_lib PUBLIC cxx_std_17)
            target_link_libraries(temp_redis_lib PUBLIC
                pthread
                ${REDIS_LIBRARIES}
            )

            target_link_libraries(common_modules_comprehensive_test temp_redis_lib)
            target_compile_definitions(common_modules_comprehensive_test PRIVATE REDIS_FOUND)
            message(STATUS "Redis found for common modules test: ${REDIS_LIBRARIES}")
        else()
            message(STATUS "Redis not found. Redis tests will be skipped in common modules test.")
            message(STATUS "To enable Redis tests, install hiredis library and rerun cmake.")
            message(STATUS "  Ubuntu/Debian: sudo apt-get install libhiredis-dev")
            message(STATUS "  CentOS/RHEL: sudo yum install hiredis-devel")
        endif()

        # 添加测试
        add_test(NAME CommonModulesTest COMMAND common_modules_comprehensive_test)
        set_tests_properties(CommonModulesTest PROPERTIES
            TIMEOUT 60  # 1分钟超时
            PASS_REGULAR_EXPRESSION "成功率: 100.00%"
        )

        message(STATUS "Added CommonModulesTest")
    else()
        message(WARNING "Skipping CommonModulesTest due to missing common module sources")
    endif()
else()
    message(WARNING "common_modules_comprehensive_test.cpp not found")
endif()

# Config模块综合测试
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/config_module_comprehensive_test.cpp" AND CONFIG_LIB)
    # 使用已经创建的Config库

    # 创建Config模块综合测试
        add_executable(config_module_comprehensive_test config_module_comprehensive_test.cpp)

        target_include_directories(config_module_comprehensive_test PRIVATE
            ${CMAKE_SOURCE_DIR}/include
            ${CMAKE_SOURCE_DIR}/include/common
        )

        target_compile_features(config_module_comprehensive_test PRIVATE cxx_std_17)

        # 链接所有必要的库
        target_link_libraries(config_module_comprehensive_test
            ${CONFIG_LIB}
            ${LOGGER_LIB}
            ${THREAD_POOL_LIB}  # 添加ThreadPool库，因为Logger依赖它
            pthread
        )

        # 添加文件系统库支持（C++17 filesystem）
        if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "9.0")
            target_link_libraries(config_module_comprehensive_test stdc++fs)
        endif()

        # 复制测试配置文件到构建目录
        configure_file(${CMAKE_CURRENT_SOURCE_DIR}/test_config_main.yml
                      ${CMAKE_CURRENT_BINARY_DIR}/test_config_main.yml COPYONLY)
        configure_file(${CMAKE_CURRENT_SOURCE_DIR}/test_config_main.json
                      ${CMAKE_CURRENT_BINARY_DIR}/test_config_main.json COPYONLY)
        configure_file(${CMAKE_CURRENT_SOURCE_DIR}/test_config.env
                      ${CMAKE_CURRENT_BINARY_DIR}/test_config.env COPYONLY)

        # 添加测试
        add_test(NAME ConfigModuleTest COMMAND config_module_comprehensive_test)
        set_tests_properties(ConfigModuleTest PROPERTIES
            TIMEOUT 120  # 2分钟超时
            PASS_REGULAR_EXPRESSION "成功率: 9[0-9]\\.[0-9][0-9]%"  # 允许90%以上成功率
            WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
        )

        message(STATUS "Added ConfigModuleTest")
else()
    message(WARNING "config_module_comprehensive_test.cpp not found or CONFIG_LIB not available")
endif()

# ==================== ThreadPool专项测试 ====================
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/thread_pool_comprehensive_test.cpp" AND TARGET ${THREAD_POOL_LIB})
    add_executable(thread_pool_comprehensive_test thread_pool_comprehensive_test.cpp)

    target_include_directories(thread_pool_comprehensive_test PRIVATE
        ${CMAKE_SOURCE_DIR}/include
    )

    target_compile_features(thread_pool_comprehensive_test PRIVATE cxx_std_17)

    target_link_libraries(thread_pool_comprehensive_test
        ${THREAD_POOL_LIB}
        ${CONFIG_LIB}
        ${LOGGER_LIB}
        pthread
    )

    # 添加ThreadPoolTest
    add_test(NAME ThreadPoolTest COMMAND thread_pool_comprehensive_test)
    set_tests_properties(ThreadPoolTest PROPERTIES
        TIMEOUT 180  # 3分钟超时
        PASS_REGULAR_EXPRESSION "测试总结: [0-9]+/[0-9]+ 通过"
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )

    message(STATUS "Added ThreadPool comprehensive test")
else()
    message(WARNING "thread_pool_comprehensive_test.cpp not found or THREAD_POOL_LIB not available")
endif()

# ==================== TaskScheduler专项测试 ====================
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/task_scheduler_comprehensive_test.cpp" AND THREAD_POOL_LIB AND TASK_SCHEDULER_LIB)
    add_executable(task_scheduler_comprehensive_test task_scheduler_comprehensive_test.cpp)

    target_include_directories(task_scheduler_comprehensive_test PRIVATE
        ${CMAKE_SOURCE_DIR}/include
    )

    target_compile_features(task_scheduler_comprehensive_test PRIVATE cxx_std_17)

    target_link_libraries(task_scheduler_comprehensive_test
        ${TASK_SCHEDULER_LIB}
        ${THREAD_POOL_LIB}
        ${CONFIG_LIB}
        ${LOGGER_LIB}
        pthread
    )

    # 添加TaskSchedulerTest
    add_test(NAME TaskSchedulerTest COMMAND task_scheduler_comprehensive_test)
    set_tests_properties(TaskSchedulerTest PROPERTIES
        TIMEOUT 300  # 5分钟超时
        PASS_REGULAR_EXPRESSION "测试总结: [0-9]+/[0-9]+ 通过"
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )

    message(STATUS "Added TaskScheduler comprehensive test")
else()
    message(WARNING "task_scheduler_comprehensive_test.cpp not found or required libraries not available")
endif()

# ==================== Logger专项测试 ====================
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/logger_comprehensive_test.cpp" AND TARGET ${LOGGER_LIB})
    add_executable(logger_comprehensive_test logger_comprehensive_test.cpp)

    target_include_directories(logger_comprehensive_test PRIVATE
        ${CMAKE_SOURCE_DIR}/include
    )

    target_compile_features(logger_comprehensive_test PRIVATE cxx_std_17)

    target_link_libraries(logger_comprehensive_test
        ${LOGGER_LIB}
        ${CONFIG_LIB}
        ${THREAD_POOL_LIB}
        pthread
    )

    # 添加LoggerTest
    add_test(NAME LoggerTest COMMAND logger_comprehensive_test)
    set_tests_properties(LoggerTest PROPERTIES
        TIMEOUT 600  # 10分钟超时（包含性能测试）
        PASS_REGULAR_EXPRESSION "测试总结: [0-9]+/[0-9]+ 通过"
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )

    message(STATUS "Added Logger comprehensive test")
else()
    message(WARNING "logger_comprehensive_test.cpp not found or LOGGER_LIB not available")
endif()



# ==================== MySQL综合测试 ====================
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/mysql_comprehensive_test.cpp" AND DATABASE_LIB AND THREAD_POOL_LIB)
    add_executable(mysql_comprehensive_test mysql_comprehensive_test.cpp)

    target_include_directories(mysql_comprehensive_test PRIVATE
        ${CMAKE_SOURCE_DIR}/include
    )

    target_compile_features(mysql_comprehensive_test PRIVATE cxx_std_17)

    target_link_libraries(mysql_comprehensive_test
        ${CONFIG_LIB}
        ${LOGGER_LIB}
        ${THREAD_POOL_LIB}
        ${DATABASE_LIB}
        ${MYSQL_LIBRARIES}
        pthread
    )

    message(STATUS "Added MySQL comprehensive test")
else()
    message(WARNING "mysql_comprehensive_test.cpp not found or required libraries not available")
endif()
# ==================== Redis综合测试 ====================
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/redis_comprehensive_test.cpp" AND DATABASE_LIB AND THREAD_POOL_LIB)
    add_executable(redis_comprehensive_test redis_comprehensive_test.cpp)

    target_include_directories(redis_comprehensive_test PRIVATE
        ${CMAKE_SOURCE_DIR}/include
    )

    target_compile_features(redis_comprehensive_test PRIVATE cxx_std_17)

    target_link_libraries(redis_comprehensive_test
        ${CONFIG_LIB}
        ${LOGGER_LIB}
        ${THREAD_POOL_LIB}
        ${DATABASE_LIB}
        hiredis  # Redis客户端库
        pthread
    )

    message(STATUS "Added Redis comprehensive test")
else()
    message(WARNING "redis_comprehensive_test.cpp not found or required libraries not available")
endif()







# ==================== 自定义测试目标 ====================
# 运行所有测试
add_custom_target(run_all_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose
        DEPENDS
        $<$<TARGET_EXISTS:network_comprehensive_test>:network_comprehensive_test>
        $<$<TARGET_EXISTS:kafka_comprehensive_test>:kafka_comprehensive_test>
        $<$<TARGET_EXISTS:common_modules_comprehensive_test>:common_modules_comprehensive_test>
        $<$<TARGET_EXISTS:config_module_comprehensive_test>:config_module_comprehensive_test>
        COMMENT "Running all module tests"
)

# 快速测试（带超时）
add_custom_target(run_quick_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --timeout 60 --verbose
        DEPENDS
        $<$<TARGET_EXISTS:network_comprehensive_test>:network_comprehensive_test>
        $<$<TARGET_EXISTS:kafka_comprehensive_test>:kafka_comprehensive_test>
        $<$<TARGET_EXISTS:common_modules_comprehensive_test>:common_modules_comprehensive_test>
        $<$<TARGET_EXISTS:config_module_comprehensive_test>:config_module_comprehensive_test>
        COMMENT "Running quick tests"
)

# 运行网络测试
add_custom_target(run_network_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "Network"
        DEPENDS
        $<$<TARGET_EXISTS:network_comprehensive_test>:network_comprehensive_test>
        COMMENT "Running network module tests only"
)

# 运行Kafka测试
add_custom_target(run_kafka_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "Kafka"
        DEPENDS
        $<$<TARGET_EXISTS:kafka_comprehensive_test>:kafka_comprehensive_test>
        COMMENT "Running Kafka module tests only"
)

# 运行通用模块测试
add_custom_target(run_common_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "CommonModules"
        DEPENDS
        $<$<TARGET_EXISTS:common_modules_comprehensive_test>:common_modules_comprehensive_test>
        COMMENT "Running common modules tests only"
)

# 运行Config模块测试
add_custom_target(run_config_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "Config"
        DEPENDS
        $<$<TARGET_EXISTS:config_module_comprehensive_test>:config_module_comprehensive_test>
        COMMENT "Running Config module tests only"
)

# 运行ThreadPool模块测试
add_custom_target(run_threadpool_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "ThreadPool"
        DEPENDS
        $<$<TARGET_EXISTS:thread_pool_comprehensive_test>:thread_pool_comprehensive_test>
        COMMENT "Running ThreadPool module tests only"
)

# 运行TaskScheduler模块测试
add_custom_target(run_taskscheduler_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "TaskScheduler"
        DEPENDS
        $<$<TARGET_EXISTS:task_scheduler_comprehensive_test>:task_scheduler_comprehensive_test>
        COMMENT "Running TaskScheduler module tests only"
)

# 运行Logger模块测试
add_custom_target(run_logger_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "Logger"
        DEPENDS
        $<$<TARGET_EXISTS:logger_comprehensive_test>:logger_comprehensive_test>
        COMMENT "Running Logger module tests only"
)

# 直接运行Config模块测试（不通过CTest）
add_custom_target(run_config_direct
        COMMAND $<TARGET_FILE:config_module_comprehensive_test>
        DEPENDS config_module_comprehensive_test
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
        COMMENT "Running Config module test directly"
)

# 构建并运行Config模块测试
add_custom_target(build_and_test_config
        COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target config_module_comprehensive_test
        COMMAND $<TARGET_FILE:config_module_comprehensive_test>
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
        COMMENT "Building and running Config module test"
)



# ==================== 测试配置 ====================
# 设置测试输出目录
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)

# 创建测试报告目录
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/test_reports)

# ==================== 帮助信息 ====================
add_custom_target(test_help
        COMMAND ${CMAKE_COMMAND} -E echo ""
        COMMAND ${CMAKE_COMMAND} -E echo "=== 模块测试帮助 ==="
        COMMAND ${CMAKE_COMMAND} -E echo ""
        COMMAND ${CMAKE_COMMAND} -E echo "可用的测试目标:"
        COMMAND ${CMAKE_COMMAND} -E echo "  make test                - 运行所有测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_all_tests      - 运行所有测试（详细输出）"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_quick_tests    - 运行快速测试（60秒超时）"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_network_tests  - 仅运行网络模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_kafka_tests    - 仅运行Kafka模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_common_tests   - 仅运行通用模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_config_tests   - 仅运行Config模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_threadpool_tests - 仅运行ThreadPool模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_taskscheduler_tests - 仅运行TaskScheduler模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_logger_tests - 仅运行Logger模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_http_module_tests - 仅运行HTTP模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  make run_http_tests     - 运行HTTP综合测试"
        COMMAND ${CMAKE_COMMAND} -E echo ""
        COMMAND ${CMAKE_COMMAND} -E echo "测试可执行文件:"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:network_comprehensive_test>:  ./network_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:kafka_comprehensive_test>:  ./kafka_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:common_modules_comprehensive_test>:  ./common_modules_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:config_module_comprehensive_test>:  ./config_module_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:thread_pool_comprehensive_test>:  ./thread_pool_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:task_scheduler_comprehensive_test>:  ./task_scheduler_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:logger_comprehensive_test>:  ./logger_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo "$<$<TARGET_EXISTS:http_module_comprehensive_test>:  ./http_module_comprehensive_test>"
        COMMAND ${CMAKE_COMMAND} -E echo ""
        COMMAND ${CMAKE_COMMAND} -E echo "测试命令:"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest --verbose         - 详细测试输出"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest --timeout 60      - 带超时的测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R Network        - 仅运行网络测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R Kafka          - 仅运行Kafka测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R CommonModules  - 仅运行通用模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R Config         - 仅运行Config模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R ThreadPool     - 仅运行ThreadPool模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R TaskScheduler  - 仅运行TaskScheduler模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R Logger         - 仅运行Logger模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo "  ctest -R Http           - 仅运行HTTP模块测试"
        COMMAND ${CMAKE_COMMAND} -E echo ""
        COMMENT "Displaying test help information"
)

# ==================== 配置信息输出 ====================
message(STATUS "")
message(STATUS "=== 测试配置总结 ===")
message(STATUS "Platform: ${CMAKE_SYSTEM_NAME}")
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS "Build Type: ${CMAKE_BUILD_TYPE}")
message(STATUS "Network Library: ${NETWORK_LIB}")
message(STATUS "Logger Library: ${LOGGER_LIB}")
if(PLATFORM_WINDOWS)
    message(STATUS "Windows-specific tests: Disabled")
    message(STATUS "Cross-platform tests: Limited")
else()
    message(STATUS "Linux-specific tests: Enabled")
    message(STATUS "Full test suite: Available")
endif()
message(STATUS "Test output directory: ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
message(STATUS "")
message(STATUS "Run 'make test_help' for usage information")
message(STATUS "========================")

# ==================== 网络模块综合测试增强配置 ====================
message(STATUS "")
message(STATUS "Enhancing Network Module Comprehensive Tests configuration...")

# 检查是否已经存在network_comprehensive_test目标
if(TARGET network_comprehensive_test)
    message(STATUS "Network comprehensive test target already exists, enhancing configuration...")

    # 查找OpenSSL（用于配置哈希计算）
    find_package(OpenSSL)
    if(OpenSSL_FOUND)
        message(STATUS "Found OpenSSL: ${OPENSSL_VERSION} - Enabling SHA256 support")
        target_compile_definitions(network_comprehensive_test PRIVATE USE_OPENSSL)
        target_link_libraries(network_comprehensive_test OpenSSL::SSL OpenSSL::Crypto)
    else()
        message(STATUS "OpenSSL not found - Using simplified hash implementation")
    endif()

    # 查找yaml-cpp（用于配置文件解析）
    find_package(PkgConfig)
    if(PkgConfig_FOUND)
        pkg_check_modules(YAML_CPP yaml-cpp)
        if(YAML_CPP_FOUND)
            message(STATUS "Found yaml-cpp - Enabling YAML config support")
            target_compile_definitions(network_comprehensive_test PRIVATE USE_YAML_CPP)
            target_link_libraries(network_comprehensive_test ${YAML_CPP_LIBRARIES})
            target_include_directories(network_comprehensive_test PRIVATE ${YAML_CPP_INCLUDE_DIRS})
        endif()
    endif()

    # 复制测试配置文件
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/test_network_config.yaml")
        configure_file(
            "${CMAKE_CURRENT_SOURCE_DIR}/test_network_config.yaml"
            "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_network_config.yaml"
            COPYONLY
        )
        message(STATUS "Copied test configuration file")
    endif()

    # 添加额外的CTest配置（使用不同的测试名称避免冲突）
    add_test(
        NAME NetworkModuleEnhancedTest
        COMMAND network_comprehensive_test
        WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}
    )

    # 设置测试属性
    set_tests_properties(NetworkModuleEnhancedTest PROPERTIES
        ENVIRONMENT "NETWORK_TEST_MODE=1;LOG_LEVEL=INFO"
        TIMEOUT 300  # 5分钟超时
        LABELS "network;comprehensive;performance;enhanced"
    )

    # 自定义目标：运行网络模块综合测试
    if(NOT TARGET run_network_comprehensive_test)
        add_custom_target(run_network_comprehensive_test
            COMMAND network_comprehensive_test
            DEPENDS network_comprehensive_test
            WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}
            COMMENT "Running comprehensive network module tests"
        )
    endif()

    # 自定义目标：运行网络性能测试
    if(NOT TARGET run_network_performance_test)
        add_custom_target(run_network_performance_test
            COMMAND network_comprehensive_test --performance-only
            DEPENDS network_comprehensive_test
            WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}
            COMMENT "Running network performance tests only"
        )
    endif()

    message(STATUS "Network comprehensive test enhanced successfully")
    message(STATUS "Available enhanced network test targets:")
    message(STATUS "  - network_comprehensive_test (existing)")
    message(STATUS "  - run_network_comprehensive_test")
    message(STATUS "  - run_network_performance_test")

else()
    message(WARNING "Network comprehensive test target not found - basic configuration may be missing")
endif()

message(STATUS "Network Module Comprehensive Tests enhancement complete")
message(STATUS "========================")

# ==================== HTTP模块综合测试配置 ====================
message(STATUS "")
message(STATUS "Configuring HTTP Module Comprehensive Tests...")

# 查找Google Test
find_package(GTest QUIET)
if(NOT GTest_FOUND)
    message(STATUS "GTest not found for HTTP tests, using FetchContent...")
    include(FetchContent)
    FetchContent_Declare(
        googletest
        URL https://github.com/google/googletest/archive/03597a01ee50ed33e9fd7188ec8e5ef0a4c8bb8c.zip
        DOWNLOAD_EXTRACT_TIMESTAMP true
    )
    set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
    FetchContent_MakeAvailable(googletest)

    # 创建别名以保持一致性
    if(TARGET gtest AND NOT TARGET GTest::gtest)
        add_library(GTest::gtest ALIAS gtest)
    endif()
    if(TARGET gtest_main AND NOT TARGET GTest::gtest_main)
        add_library(GTest::gtest_main ALIAS gtest_main)
    endif()
endif()

# HTTP模块源文件列表（包含所有依赖模块）
set(HTTP_MODULE_TEST_SOURCES
    # HTTP模块核心文件
    ${CMAKE_SOURCE_DIR}/src/common/http/http_request.cpp
    ${CMAKE_SOURCE_DIR}/src/common/http/http_response.cpp
    ${CMAKE_SOURCE_DIR}/src/common/http/http_server.cpp
    ${CMAKE_SOURCE_DIR}/src/common/http/http_router.cpp
    ${CMAKE_SOURCE_DIR}/src/common/http/http_session.cpp
    ${CMAKE_SOURCE_DIR}/src/common/http/http_middleware.cpp

    # 依赖模块文件
    ${CMAKE_SOURCE_DIR}/src/common/logger/logger.cpp
    ${CMAKE_SOURCE_DIR}/src/common/config/config_manager.cpp

    # 网络模块文件（HTTP模块依赖）
    ${CMAKE_SOURCE_DIR}/src/common/network/socket.cpp
    ${CMAKE_SOURCE_DIR}/src/common/network/inet_address.cpp
    ${CMAKE_SOURCE_DIR}/src/common/network/channel.cpp
    ${CMAKE_SOURCE_DIR}/src/common/network/event_loop.cpp
    ${CMAKE_SOURCE_DIR}/src/common/network/epoll.cpp

    # 线程池模块文件（HTTP模块依赖）
    ${CMAKE_SOURCE_DIR}/src/common/thread_pool/thread_pool.cpp
)

# 检查源文件是否存在并过滤
set(HTTP_EXISTING_SOURCES "")
foreach(source_file ${HTTP_MODULE_TEST_SOURCES})
    if(EXISTS ${source_file})
        list(APPEND HTTP_EXISTING_SOURCES ${source_file})
        message(STATUS "Found HTTP source: ${source_file}")
    else()
        message(WARNING "HTTP source file not found: ${source_file}")
    endif()
endforeach()

# 创建HTTP模块测试库
if(HTTP_EXISTING_SOURCES)
    add_library(http_module_test_lib STATIC ${HTTP_EXISTING_SOURCES})

    target_include_directories(http_module_test_lib PUBLIC
        ${CMAKE_SOURCE_DIR}/include
        ${CMAKE_SOURCE_DIR}/src
    )

    target_link_libraries(http_module_test_lib
        Threads::Threads
        ${CMAKE_DL_LIBS}
    )

    # 链接已存在的库
    if(TARGET temp_logger_lib)
        target_link_libraries(http_module_test_lib temp_logger_lib)
    endif()

    if(TARGET config_lib)
        target_link_libraries(http_module_test_lib config_lib)
    endif()

    # 链接网络模块库（如果存在）
    if(TARGET network_lib)
        target_link_libraries(http_module_test_lib network_lib)
    endif()

    # 链接线程池模块库（如果存在）
    if(TARGET thread_pool_lib)
        target_link_libraries(http_module_test_lib thread_pool_lib)
    endif()

    # 链接nlohmann_json（如果可用）
    if(TARGET nlohmann_json::nlohmann_json)
        target_link_libraries(http_module_test_lib nlohmann_json::nlohmann_json)
    elseif(TARGET nlohmann_json)
        target_link_libraries(http_module_test_lib nlohmann_json)
    endif()

    # 设置编译定义
    target_compile_definitions(http_module_test_lib PRIVATE
        HTTP_MODULE_VERSION="2.0.0"
        $<$<CONFIG:Debug>:HTTP_DEBUG_MODE>
    )

    message(STATUS "HTTP module test library created successfully")
else()
    message(FATAL_ERROR "No HTTP module source files found!")
endif()

# HTTP综合测试可执行文件
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/http_module_comprehensive_test.cpp)
    add_executable(http_module_comprehensive_test
        ${CMAKE_CURRENT_SOURCE_DIR}/http_module_comprehensive_test.cpp
    )

    target_link_libraries(http_module_comprehensive_test
        http_module_test_lib
        GTest::gtest
        GTest::gtest_main
        Threads::Threads
    )

    # 链接nlohmann_json（如果可用）
    if(TARGET nlohmann_json::nlohmann_json)
        target_link_libraries(http_module_comprehensive_test nlohmann_json::nlohmann_json)
    elseif(TARGET nlohmann_json)
        target_link_libraries(http_module_comprehensive_test nlohmann_json)
    endif()

    # 测试编译定义
    target_compile_definitions(http_module_comprehensive_test PRIVATE
        GTEST_HAS_PTHREAD=1
        HTTP_TEST_MODE=1
        HTTP_TEST_DATA_DIR="${CMAKE_CURRENT_BINARY_DIR}/test_data"
    )

    # 注册测试
    add_test(NAME HttpModuleComprehensiveTest
             COMMAND http_module_comprehensive_test
             WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

    set_tests_properties(HttpModuleComprehensiveTest PROPERTIES
        TIMEOUT 300
        LABELS "comprehensive;integration;http"
    )

    # 添加到运行所有测试的目标
    add_dependencies(run_all_tests http_module_comprehensive_test)

    # 创建HTTP专项测试目标
    add_custom_target(run_http_module_tests
        COMMAND ${CMAKE_CTEST_COMMAND} --verbose -R "Http"
        DEPENDS http_module_comprehensive_test
        COMMENT "Running HTTP module tests only"
    )

    # 创建HTTP测试运行目标
    add_custom_target(run_http_tests
        COMMAND http_module_comprehensive_test
        DEPENDS http_module_comprehensive_test
        COMMENT "Running HTTP module comprehensive tests"
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )

    # 创建测试数据目录
    add_custom_target(create_http_test_data_dir
        COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/test_data
        COMMENT "Creating HTTP test data directory"
    )
    add_dependencies(http_module_comprehensive_test create_http_test_data_dir)

    message(STATUS "HTTP module comprehensive test configured successfully")
    message(STATUS "Available HTTP test targets:")
    message(STATUS "  - http_module_comprehensive_test")
    message(STATUS "  - run_http_module_tests")
    message(STATUS "  - run_http_tests")
else()
    message(WARNING "HTTP module comprehensive test source file not found")
endif()

message(STATUS "HTTP Module Tests configuration complete")
message(STATUS "========================")

# ==================== API Gateway 测试配置 ====================
message(STATUS "========================")
message(STATUS "Configuring API Gateway Tests")
message(STATUS "========================")

# 检查API Gateway源文件
set(API_GATEWAY_SOURCES
    "${CMAKE_SOURCE_DIR}/src/core_services/api_gateway/api_gateway.cpp"
    "${CMAKE_SOURCE_DIR}/src/core_services/api_gateway/load_balancer.cpp"
    "${CMAKE_SOURCE_DIR}/src/core_services/api_gateway/rate_limiter.cpp"
    "${CMAKE_SOURCE_DIR}/src/core_services/api_gateway/circuit_breaker.cpp"
    "${CMAKE_SOURCE_DIR}/src/core_services/api_gateway/service_route.cpp"
)

# 验证API Gateway源文件存在
set(API_GATEWAY_SOURCES_FOUND TRUE)
foreach(SOURCE ${API_GATEWAY_SOURCES})
    if(EXISTS ${SOURCE})
        message(STATUS "Found API Gateway source: ${SOURCE}")
    else()
        message(WARNING "API Gateway source not found: ${SOURCE}")
        set(API_GATEWAY_SOURCES_FOUND FALSE)
    endif()
endforeach()

# 创建API Gateway测试库
if(API_GATEWAY_SOURCES_FOUND)
    add_library(api_gateway_test_lib STATIC ${API_GATEWAY_SOURCES})

    target_include_directories(api_gateway_test_lib PUBLIC
        ${CMAKE_SOURCE_DIR}/include
        ${CMAKE_SOURCE_DIR}/include/common
        ${CMAKE_SOURCE_DIR}/include/core_services
        ${CMAKE_SOURCE_DIR}/include/core_services/api_gateway
    )

    # 链接依赖库
    target_link_libraries(api_gateway_test_lib PUBLIC
        ${LOGGER_LIB}
        ${CONFIG_LIB}
        ${THREAD_POOL_LIB}
        pthread
    )

    # 链接HTTP模块（如果存在）
    if(TARGET http_module_test_lib)
        target_link_libraries(api_gateway_test_lib PUBLIC http_module_test_lib)
    endif()

    # 链接nlohmann_json（如果可用）
    if(TARGET nlohmann_json::nlohmann_json)
        target_link_libraries(api_gateway_test_lib PUBLIC nlohmann_json::nlohmann_json)
    elseif(TARGET nlohmann_json)
        target_link_libraries(api_gateway_test_lib PUBLIC nlohmann_json)
    endif()

    # 设置编译定义
    target_compile_definitions(api_gateway_test_lib PRIVATE
        API_GATEWAY_VERSION="1.0.0"
        $<$<CONFIG:Debug>:API_GATEWAY_DEBUG_MODE>
    )

    message(STATUS "API Gateway test library created successfully")
else()
    message(FATAL_ERROR "No API Gateway source files found!")
endif()

# API Gateway全面测试可执行文件
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/api_gateway_comprehensive_test.cpp)
    add_executable(api_gateway_comprehensive_test
        ${CMAKE_CURRENT_SOURCE_DIR}/api_gateway_comprehensive_test.cpp
    )

    target_link_libraries(api_gateway_comprehensive_test
        api_gateway_test_lib
        ${LOGGER_LIB}
        ${CONFIG_LIB}
        ${THREAD_POOL_LIB}
        pthread
    )

    # 链接nlohmann_json（如果可用）
    if(TARGET nlohmann_json::nlohmann_json)
        target_link_libraries(api_gateway_comprehensive_test nlohmann_json::nlohmann_json)
    elseif(TARGET nlohmann_json)
        target_link_libraries(api_gateway_comprehensive_test nlohmann_json)
    endif()

    # 测试编译定义
    target_compile_definitions(api_gateway_comprehensive_test PRIVATE
        API_GATEWAY_TEST_MODE=1
        API_GATEWAY_TEST_DATA_DIR="${CMAKE_CURRENT_BINARY_DIR}/test_data"
        TESTING=1  # 定义TESTING宏，用于测试环境配置
    )

    # 注册测试
    add_test(NAME ApiGatewayComprehensiveTest
             COMMAND api_gateway_comprehensive_test
             WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

    set_tests_properties(ApiGatewayComprehensiveTest PROPERTIES
        TIMEOUT 600  # 10分钟超时，因为包含性能测试
        LABELS "comprehensive;integration;api_gateway"
    )

    # 添加到运行所有测试的目标
    if(TARGET run_all_tests)
        add_dependencies(run_all_tests api_gateway_comprehensive_test)
    endif()

    # 创建API Gateway专项测试目标
    add_custom_target(run_api_gateway_tests
        COMMAND api_gateway_comprehensive_test
        DEPENDS api_gateway_comprehensive_test
        COMMENT "Running API Gateway comprehensive tests"
        WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    )

    # 创建测试数据目录
    add_custom_target(create_api_gateway_test_data_dir
        COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/test_data
        COMMENT "Creating API Gateway test data directory"
    )
    add_dependencies(api_gateway_comprehensive_test create_api_gateway_test_data_dir)

    message(STATUS "API Gateway comprehensive test configured successfully")
    message(STATUS "Available API Gateway test targets:")
    message(STATUS "  - api_gateway_comprehensive_test")
    message(STATUS "  - run_api_gateway_tests")
else()
    message(WARNING "API Gateway comprehensive test source file not found")
endif()

# API Gateway配置测试（如果存在）
if(EXISTS "${CMAKE_SOURCE_DIR}/test/api_gateway_config_test.cpp")
    add_executable(api_gateway_config_test
        ${CMAKE_SOURCE_DIR}/test/api_gateway_config_test.cpp
    )

    target_link_libraries(api_gateway_config_test
        api_gateway_test_lib
        ${LOGGER_LIB}
        ${CONFIG_LIB}
        pthread
    )

    # 注册配置测试
    add_test(NAME ApiGatewayConfigTest
             COMMAND api_gateway_config_test
             WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

    set_tests_properties(ApiGatewayConfigTest PROPERTIES
        TIMEOUT 60
        LABELS "unit;config;api_gateway"
    )

    message(STATUS "API Gateway config test configured successfully")
endif()

# RateLimiter安全测试
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/rate_limiter_safe_test.cpp)
    add_executable(rate_limiter_safe_test
        ${CMAKE_CURRENT_SOURCE_DIR}/rate_limiter_safe_test.cpp
    )

    target_link_libraries(rate_limiter_safe_test
        api_gateway_test_lib
        ${LOGGER_LIB}
        ${CONFIG_LIB}
        ${THREAD_POOL_LIB}
        pthread
    )

    # 链接nlohmann_json（如果可用）
    if(TARGET nlohmann_json::nlohmann_json)
        target_link_libraries(rate_limiter_safe_test nlohmann_json::nlohmann_json)
    elseif(TARGET nlohmann_json)
        target_link_libraries(rate_limiter_safe_test nlohmann_json)
    endif()

    # 设置编译定义（启用测试模式）
    target_compile_definitions(rate_limiter_safe_test PRIVATE
        TESTING=1
        RATE_LIMITER_TEST_MODE=1
    )

    # 注册测试
    add_test(NAME RateLimiterSafeTest
             COMMAND rate_limiter_safe_test
             WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

    set_tests_properties(RateLimiterSafeTest PROPERTIES
        TIMEOUT 120  # 2分钟超时
        LABELS "safe;rate_limiter;deadlock_fix"
    )

    message(STATUS "RateLimiter safe test configured successfully")
endif()

message(STATUS "API Gateway Tests configuration complete")
message(STATUS "========================")